package cn.org.donald.framework.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Donald
 * @since : 2020/11/7 14:23
 */
public class ListUtil {

    /**
     * 判断集合是否为空或存在 一个全为null或""的对象
     * @param list 集合
     * @param <T> 数据实体类
     * @return boolean
     */
    public static <T> boolean isEmptyOrHasClassFieldAllEmpty(List<T> list){
        if (list==null || list.isEmpty()){
            return true;
        }
        for (T t : list) {
            try {
                Class<?> clazz = t.getClass();
                Field[] declaredFields = clazz.getDeclaredFields();
                int i = 0;
                int f = declaredFields.length;
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (!"serialVersionUID".equals(name)){
                        declaredField.setAccessible(true);
                        Object o = declaredField.get(t);
                        if (o == null || "".equals(o)){
                            i++;
                        }
                    }else {
                        f--;
                    }
                }
                if (i == f){
                    return true;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return false;
    }


    /**
     * 将继承entity集合的值 复制给继承entity的vo类集合
     * @param sourceList entity集合
     * @param target    vo对象
     * @param <S> entity泛型
     * @param <T> vo泛型
     * @return 返回vo类集合
     */
    @SuppressWarnings("unchecked")
    public static <S,T extends S> List<T> copyEntityToVo(List<S> sourceList,T target){
        if (sourceList == null || sourceList.isEmpty()){
            return new ArrayList<>();
        }
        List<T> targetList = new ArrayList<>(sourceList.size());
        String name = target.getClass().getName();
        for (S source : sourceList) {
            try {
                T t = (T) Class.forName(name).newInstance();
                BeanUtil.copyProperties(source,t);
                targetList.add(t);
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return targetList;
    }

}
